package com.project;

import com.project.config.MVCConfig;
import com.project.filter.CharFilter;
import com.project.filter.LoginFilter;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

public class MainFilterUpload {
    public MainFilterUpload(){
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);// 设置Tomcat端口
        tomcat.getConnector();// 引导HTTP引擎Context

        //定义WEB上下文
        Context context = tomcat.addContext("", null);//定义上下文

        //注册过滤器
        this.registerFilter(new LoginFilter(),"/html/index.html",context);
        this.registerFilter(new CharFilter(),"*",context);


        try {
            //创建DispatcherServlet前端控制器
            WebApplicationContext webContext = this.createApplicationContext(
                    context.getServletContext());
            DispatcherServlet dispatcherServlet =
                    new DispatcherServlet(webContext);
            //注册前端控制器
            Wrapper servletWrapper =  Tomcat.addServlet(
                    context, "dispatcherServlet", dispatcherServlet);
            servletWrapper.setLoadOnStartup(0);
            servletWrapper.addMapping("/*");


            tomcat.start();//启动tomcat
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 注册过滤器方法
     * @param filter 过滤器
     * @param urlPattrn 设置过滤的范围
     * @param context WEB上下文
     */
    private void registerFilter(Filter filter,String urlPattrn,Context context){
        //注册过滤器
        FilterDef fd = new FilterDef();
        fd.setFilter(filter);//设置过滤器
        //getSimpleName() 类名
        fd.setFilterName(filter.getClass().getSimpleName());//过滤器的名称

        FilterMap fm = new FilterMap();
        fm.setFilterName(filter.getClass().getSimpleName());

        //设置过滤的范围
        fm.addURLPattern(urlPattrn);

        //注册过滤器和过滤范围
        context.addFilterDef(fd);
        context.addFilterMap(fm);

    }

    public static WebApplicationContext createApplicationContext(
            ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx
                = new AnnotationConfigWebApplicationContext();
        //注册配置类
        ctx.register(MVCConfig.class);

        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    public static void main(String[] args) {
        new MainFilterUpload();
    }
}
